package com.qq.first_project.controller.common;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qq.first_project.common.R;
import com.qq.first_project.entity.Comment;
import com.qq.first_project.entity.vo.CommentVo;
import com.qq.first_project.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Qiu
 * @since 2023-01-30
 */
@RestController
@CrossOrigin //跨域
@RequestMapping("/common/comment")
public class CommentController {
    @Autowired
    private CommentService commentService;

    /**
     * 查询某文章的所有评论
     * @return
     */
    @GetMapping("/list")
    R comments(@RequestParam Long blogId) {
        List<Comment> comments = commentService.listComment(blogId);
        return R.ok().data("data",comments).message("获取成功");
    }

    /**
     * 查询所有评论
     * @return
     */
    @GetMapping("/page-list")
    R listAll(ModelMap modelMap,@RequestParam("current") int num,@RequestParam("pageSize") int size,String name ) {
        Page<CommentVo> page = new Page<>(num,size);
        IPage<CommentVo> comments = commentService.listAll(page,name);
        modelMap.addAttribute("page",comments);
        return R.ok().data("data",comments).message("获取成功");
    }

    /**
     * 新增评论
     * @param comment
     * @return
     */
    @PostMapping("/save")
    R post(Comment comment) {
        int result = commentService.saveComment(comment);
        if (result != 0) {
            return R.ok().message("保存成功");
        } else {
            return R.error().message("保存失败");
        }
    }


    /**
     * 删除
     * @param id
     * @return
     */
    @PostMapping("delById")
    R delById(Long id){
        boolean result = commentService.removeById(id);
        if (result) {
            return R.ok().message("删除成功");
        } else {
            return R.error().message("删除失败");
        }
    }

    /**
     * 修改
     * @param commentVo
     * @return
     */
    @PostMapping("updateById")
    R updateById(CommentVo commentVo){
        int result = commentService.updateCommentById(commentVo);
        if (result != 0) {
            return R.ok().message("修改成功");
        } else {
            return R.error().message("数据不存在");
        }
    }
}
